package htlgkr.nodlehs;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class CreateNewSubjectActivity extends Activity {

	SQLiteDatabase db;
	NodlehsDatabase bridge = new NodlehsDatabase(this);
	boolean longD, shortD = false;
	EditText txtnewDescS;
	EditText txtnewDescL;
	EditText txtnewDesc;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsubject);
		db = bridge.getWritableDatabase();
	}

	public void addNewSubjectClick(final View v) {
		txtnewDescS = (EditText) findViewById(R.id.txtDescS);
		txtnewDescL = (EditText) findViewById(R.id.txtDescL);
		txtnewDesc = (EditText) findViewById(R.id.txtDesc);
		String descS = txtnewDescS.getText().toString();
		String descL = txtnewDescL.getText().toString();
		String desc = txtnewDesc.getText().toString();
		long id = 0;
		if(descS.length() > 0){
			shortD = true;
		}else {
			Toast.makeText(this, "Es wurde keine Kurzbezeichnung eingetragen", Toast.LENGTH_SHORT).show();
		}
		if(descL.length() > 0){
			longD = true;
		}else{
			Toast.makeText(this, "Es wurde keine Langbezeichnung eingetragen", Toast.LENGTH_SHORT).show();
		}
		if (longD && shortD) {
			SQLiteStatement stmt = db.compileStatement(DBSubjectTbl.SQL_INSERT);
			db.beginTransaction();
			try {
				stmt.bindString(1, descS);
				stmt.bindString(2, descL);
				stmt.bindString(3, desc);
				id = stmt.executeInsert();
				db.setTransactionSuccessful();

			} catch (Exception e) {
				Log.e("DBInsert Subject", e.getMessage().toString());
			} finally {
				db.endTransaction();
				db.close();
			}
			Log.i("NewSubjectActivity", descS + "_" + descL + "_" + desc);
			Log.i("NewSubjectActivity", id + "");
			gotToMain();
		}
		
	}
	
	private void gotToMain() {
		Intent i = new Intent();
		setResult(222, i);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.subjectmenu, menu);
		return true;
	}
}
